import { getUserInfo,login} from '@/api/user';
import router from '@/router';
import { getToken, setToken, removeToken } from '@/utils/auth';

const getDefaultState = () => {
  return {
    token: getToken(),
    code:localStorage.getItem('code')
  };
};

const state = getDefaultState();

const mutations = {
  
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_CODE: (state, code) => {
    state.code = code;
    localStorage.setItem('code', code);
  },
};

const actions = {
  // user login
  login({ commit, dispatch }, data) {
    return new Promise((resolve, reject) => {
      login(data)
        .then(async (response) => {
          let {token} = response.data;
          commit('SET_TOKEN', token);
          setToken(token);
          localStorage.setItem('token', token);
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  getUserInfo({ commit, dispatch }, data) {
    // return new Promise((resolve, reject) => {
    //   // console.log('data',data)
    //   getUserInfo(data)
    //     .then(async (response) => {
    //       let {mobilePhone:mobile_phone,userId:user_id,token:code} = response.data
    //       await dispatch('login',{code,user_id,mobile_phone})
    //       resolve();
    //     })
    //     .catch((error) => {
    //       reject(error);
    //     });
    // });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
